package com.cby.operation.common.util

import android.content.ClipData
import android.content.Context
import android.os.Build
import android.text.ClipboardManager
import android.text.TextUtils

/**
 * Description:ClipboardUtils
 *
 * @author 陈宝阳
 * @create 2020/8/29 10:27
 */
object ClipboardUtils {
    /**
     * 复制字符串到剪贴板
     * @param context
     * @param copyStr
     */
    fun copy(context: Context, copyStr: String?) {
        //兼容性处理3.0以前版本
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            val clipboardManager =
                context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            clipboardManager.text = copyStr
        } else {
            val clipboardManager =
                context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
            clipboardManager.setPrimaryClip(ClipData.newPlainText(null, copyStr))
        }
    }

    /**
     * 从剪贴板中获得第一个字符串
     * @param activity
     * @return
     */
    fun paste(activity: Context): String {
        var pasteStr = ""
        //兼容性处理3.0以前版本
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            val clipboardManager =
                activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            if (clipboardManager != null && clipboardManager.hasText()) {
                pasteStr = clipboardManager.text.toString()
            }
        } else {
            val clipboardManager =
                activity.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
            if (clipboardManager != null && clipboardManager.hasPrimaryClip()) {
                val text = clipboardManager.primaryClip!!.getItemAt(0).text
                pasteStr = if (TextUtils.isEmpty(text)) "" else text.toString()
            }
        }
        return pasteStr
    }
}